package br.com.fromtis.jsf.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;





public class HibernateUtil {

	private static HibernateUtil me;
	
	private SessionFactory sessionFactory;
	
	private ServiceRegistry serviceRegistry;
	
	private Session session;
	
	private HibernateUtil () {
		Configuration config = new Configuration();
		serviceRegistry = new ServiceRegistryBuilder().applySettings( config.getProperties() ).buildServiceRegistry();
		sessionFactory = config.configure("hibernate.cfg.xml").buildSessionFactory( serviceRegistry );
	}
	
	public Session getCurrentSession() {
		if( session == null  || !session.isOpen() ) {
			System.out.println( "a sessao nao esta aberta!, abrir sessao!");
			openSession();
		} 
		return session;
	}
	private Session openSession() {
		System.out.println( "tentando abrir sessao");
		session = sessionFactory.openSession();
		return session;
	}
	
	public static HibernateUtil getInstance ( ) {
		if ( me == null ) {
			me = new HibernateUtil();
			System.out.println( "Abriu uma nova instancia de HibernateUtil, entao criou uma SessionFactory");
			System.out.println( "Classe chamando uma nova instancia: " );
		}
		return me;
	}
	
}
